<template>
  <div>
    <!-- 筛选项 -->
    <div class="gl_searchBox">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p>按性别选择</p>
          <el-select v-model="PointRankListQO.GenderCode" size="mini" placeholder="请选择" @change="getPageList()">
            <el-option label="全部" value="" />
            <el-option label="男" value="M" />
            <el-option label="女" value="W" />
          </el-select>
        </el-col>
        <el-col :md="6" :lg="4">
          <p>按项目选择</p>
          <el-select v-model="PointRankListQO.CategoryId" size="mini" placeholder="请选择" @change="getPageList()">
            <el-option label="全部" value="" />
            <el-option v-for="(data, index) in eventType" :key="index" :label="data.name" :value="data.id" />
          </el-select>
        </el-col>
        <el-col :md="6" :lg="4">
          <p>选手姓名</p>
          <el-input v-model="PointRankListQO.Keyword" placeholder="请输入姓名" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :md="6" :lg="6" align="left" class="search_btn">
          <!-- 查询按钮 -->
          <el-button type="primary" size="mini" @click="getPageList()">{{ $t('button.query') }}</el-button>
          <el-button :loading="downloadTsLoading" style="margin-top: 27px" type="warning" size="mini" @click="downloadPDF()">导出积分表</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 赛事列表 -->
    <el-row :gutter="20" class="gl_mt_15">
      <el-col :span="24" style="text-align:right">
        <el-button :loading="buLoading_Integral" type="primary" size="mini" @click="updateIntegral()">更新排名</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="tableLoading" class="gl_mb_15 gl_mt_10 game_table_list" :data="tableData" stripe size="mini" style="width: 100%">
      <el-table-column prop="finalRank" align="center" label="排名" :width="80" />
      <el-table-column label="姓名" :width="130">
        <template slot-scope="{ row }">
          <img class="game_coverimg" :src="getStaticPhotoUrl(row.photoUrl)" alt="" @error="errorPhoto">
          <span style="display: inline-block;margin-left: 15px;">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="gender" align="center" label="性别" :width="80" />
      <el-table-column prop="organization" label="机构名称" :min-width="190" />
      <el-table-column prop="comment" label="参加赛事" :min-width="210" />
      <el-table-column label="金牌" align="center" :width="90">
        <template slot-scope="{ row }">
          <span>{{ row._subRankList._1 && row._subRankList._1.subRankCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银牌" align="center" :width="90">
        <template slot-scope="{ row }">
          <span>{{ row._subRankList._2 && row._subRankList._2.subRankCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="铜牌" align="center" :width="90">
        <template slot-scope="{ row }">
          <span>{{ row._subRankList._3 && row._subRankList._3.subRankCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="战绩" align="center" :width="100">
        <template slot-scope="{ row }">
          <span>{{ row.winCount }}胜/{{ row.loseCount }}负</span>
        </template>
      </el-table-column>
      <el-table-column label="胜率" align="center" :width="90">
        <template slot-scope="{ row }">
          <span>{{ (row.winPercent || row.winPercent === 0) ? Math.round(row.winPercent * 100) + '%' : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unitPoints" align="center" label="场次分" :width="90" />
      <el-table-column prop="rankPoints" align="center" label="名次分" :width="90" />
      <el-table-column prop="finalPoints" align="center" label="总分" :width="90" />
      <el-table-column prop="realPoints" align="center" label="真实积分" :width="100" />
      <el-table-column prop="operatePoints" align="center" label="已操作积分" :width="100" />
      <el-table-column fixed="right" align="center" :label="$t('table.actions')" :width="200">
        <template slot-scope="{ row }">
          <el-button icon="el-icon-plus" size="mini" circle @click="saveScore(row, 'add')" />
          <el-input-number v-model="row.point" :controls="false" size="mini" :min="1" placeholder="请输入数字" style="width: 95px;margin:0 10px" />
          <el-button icon="el-icon-minus" size="mini" circle @click="saveScore(row, 'subtract')" />
          <!-- <el-button size="mini" type="text" @click="changeScore(row)">
            <span class="gl_color_primary">积分操作</span>
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-row style="text-align: right;" class="gl_pb_15">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="PointRankListQO.MaxResultCount"
        :current-page="PointRankListQO.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
    <!-- 积分操作弹框 -->
    <el-dialog title="积分操作" class="gl_dialog_TitleLine" :visible.sync="dialogVisible_editScore" :close-on-click-modal="false" width="440px">
      <el-row class="transferBox" type="flex" justify="center">
        <el-form ref="addorRemovePointOperationDto" class="gl_form_mini gl_mt_30" :model="addorRemovePointOperationDto" :rules="categoryVO_Rules" label-position="right" style="width: 70%;">
          <el-form-item label="积分操作" prop="teamMinMaleMembersCount">
            <el-input-number v-model="addorRemovePointOperationDto.teamMinMaleMembersCount" :precision="0" placeholder="请输入数字" size="mini" controls-position="right" :min="0" />
          </el-form-item>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button size="mini" @click="dialogVisible_editScore = false">{{ $t('button.cancel') }}</el-button>
        <!-- 保存按钮 -->
        <el-button type="primary" :loading="submitLoading" size="mini" @click="saveScore">{{ $t('button.save') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import defaultGameLogo from '@/assets/images/game/game_logoDefaultPhoto.png';
import { Api_GET_EventsManagementEventResultUnifiedPointRankListQO, SiSTKWEventsManagementAddorRemovePointOperationDto } from '@/lib/form/game/swaggerForm';
import { CategoryVO_Rules } from '@/lib/validate/league';
import {
  api_GET_EventsManagementCategory,
  api_GET_EventsManagementEventResultUnifiedPointRankList, api_POST_EventsManagementPointOperationOrRemovePointOperation, api_POST_EventsManagementEventResultClearPointCacheCompetitionId
} from '@/extend/api/gameswaggerApi/app.js';

export default {
  props: {
    rankType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      categoryVO_Rules: new CategoryVO_Rules(),
      defaultGameLogo: defaultGameLogo,
      addorRemovePointOperationDto: new SiSTKWEventsManagementAddorRemovePointOperationDto(),
      PointRankListQO: new Api_GET_EventsManagementEventResultUnifiedPointRankListQO(),
      tableData: [],
      eventType: [],
      total: 0,
      downloadTsLoading: false,
      buLoading: false,
      dialogVisible_editScore: false,
      submitLoading: false,
      tableLoading: false,
      buLoading_Integral: false,
      gameId: '',
      rowData_person: {}
    };
  },
  created() {
    this.initForm();
  },
  methods: {
    // 初始化
    initForm() {
      this.gameId = this.$route.params.parentId;
      this.PointRankListQO = new Api_GET_EventsManagementEventResultUnifiedPointRankListQO();
      this.PointRankListQO.CategoryId = '';
      this.PointRankListQO.GenderCode = '';
      this.getCategory();
    },
    // 获取项目列表
    getCategory() {
      var _this = this;
      const params = {
        CompetitionId: this.gameId,
        EventTypeCode: ''
      };
      if (this.rankType === 'All') {
        params.EventTypeCode = '';
      }
      if (this.rankType === 'Competitive') {
        params.EventTypeCode = 'Competitive';
      }
      if (this.rankType === 'NoneCompetitive') {
        params.EventTypeCode = 'NoneCompetitive';
      }
      api_GET_EventsManagementCategory(params).then(res => {
        _this.eventType = res.items;
        _this.getPageList();
      }).catch(() => {
        _this.$message({ type: 'error', message: '获取项目列表失败！' });
        _this.getPageList();
      });
    },
    // 获取赛事列表
    getPageList(page) {
      if (this.rankType === 'All') {
        this.PointRankListQO.EventTypeCode = '';
      }
      if (this.rankType === 'Competitive') {
        this.PointRankListQO.EventTypeCode = 'Competitive';
      }
      if (this.rankType === 'NoneCompetitive') {
        this.PointRankListQO.EventTypeCode = 'NoneCompetitive';
      }
      this.PointRankListQO.Type = 'Register';
      this.PointRankListQO.CompetitionId = this.gameId;
      this.PointRankListQO.IncludeFinal = false;
      this.PointRankListQO.IncludeSubRank = true;
      this.PointRankListQO.Page = page || 1;
      this.PointRankListQO.SkipCount = (this.PointRankListQO.Page - 1) * this.PointRankListQO.MaxResultCount;
      this.tableLoading = true;
      api_GET_EventsManagementEventResultUnifiedPointRankList(this.PointRankListQO).then(res => {
        var returnData = res.items;
        // 处理返回的数据
        this.tableData = this.hanldReault(returnData);
        this.total = res.totalCount;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 积分操作
    changeScore (row) {
      this.rowData_person = row;
      this.dialogVisible_editScore = true;
    },
    saveScore (row, type) {
      const _this = this;
      if (!row.point) return;
      this.tableLoading = true;
      this.addorRemovePointOperationDto.competitionId = this.gameId;
      this.addorRemovePointOperationDto.registerId = row.entityId;
      this.addorRemovePointOperationDto.point = row.point;
      this.addorRemovePointOperationDto.isAdd = type === 'add';
      api_POST_EventsManagementPointOperationOrRemovePointOperation(this.addorRemovePointOperationDto).then(() => {
        _this.$message({ type: 'success', message: '修改成功！' });
        _this.tableLoading = false;
        // _this.dialogVisible_editScore = false;
        _this.getPageList(_this.PointRankListQO.Page);
      }, error => {
        _this.tableLoading = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 更新积分
    updateIntegral () {
      const _this = this;
      this.buLoading_Integral = true;
      api_POST_EventsManagementEventResultClearPointCacheCompetitionId(this.gameId).then(() => {
        _this.$message({ type: 'success', message: '更新成功！' });
        _this.buLoading_Integral = false;
        _this.getPageList(_this.PointRankListQO.Page);
      }, error => {
        _this.buLoading_Integral = false;
        const _msg = error.error.message || error.message;
        _this.$message({ type: 'error', message: _msg });
      });
    },
    // 处理成绩
    hanldReault(eventResult) {
      const returnEventResult = [];
      for (let i = 0; i < eventResult.length; i++) {
        const item = eventResult[i];
        item._subRankList = this.hanldRank(item.subRankList);
        returnEventResult.push(item);
      }
      return returnEventResult;
    },
    // 处理排名
    hanldRank(subRankList) {
      const returnRankInfo = {};
      for (let i = 0; i < subRankList.length; i++) {
        const item = subRankList[i];
        returnRankInfo['_' + item.subRank] = item;
      }
      return returnRankInfo;
    },
    downloadPDF() {
      var _this = this;
      this.downloadTsLoading = true;
      let CategoryId = '';
      let CategoryIds = '';
      if (this.PointRankListQO.CategoryId !== '') {
        CategoryId = this.PointRankListQO.CategoryId;
      } else {
        for (let i = 0; i < this.eventType.length; i++) {
          const item = this.eventType[i].id;
          CategoryIds = CategoryIds + item;
          if (i !== this.eventType.length - 1) {
            CategoryIds = CategoryIds + ',';
          }
        }
      }
      const tempUrl = `/api/excel`;
      const fileName = '积分表' + '.xlsx';
      const params = {};
      params.ReportName = 'LeagueRank';
      params.Type = this.PointRankListQO.Type;
      params.CompetitionId = this.gameId;
      params.CategoryId = CategoryId;
      params.CategoryIds = CategoryIds;
      params.EventTypeCode = this.PointRankListQO.EventTypeCode;
      params.Keyword = this.PointRankListQO.Keyword;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, params).then(res => {
        _this.downloadTsLoading = false;
      }).catch(error => {
        _this.downloadTsLoading = false;
        errorText(error).then(function(text) {
          _this.$message({ type: 'error', message: text });
        });
      });
    },
    // 获取图片地址
    getStaticPhotoUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultGameLogo;
    },
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.PointRankListQO.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>
<style lang="scss" scoped>
  .statistics_title{
    line-height: 50px;
  }
  .statistics_label{
    text-align: right;
    font-weight: bold;
  }
  .statistics_nums{
    font-size: 40px;
    color: rgb(58, 128, 236);
    margin-bottom: 10px;
  }
  .game_table_list .game_coverimg {
    width: 74px;
    height: 74px;
    border-radius: 50%;
    vertical-align: middle;
  }
  .transferBox .el-transfer-panel__header{
    pointer-events:none
  }
  .transferBox .el-transfer-panel{
    width: 400px;
  }
  .transferBox .el-transfer-panel__header .el-checkbox__input{
    display: none;
  }
  .transferBox .el-transfer-panel__item{
    height: 80px;
    line-height: 80px;
    margin: 0 10px;
    border-bottom: 1px solid #dfe6ec;
  }
</style>
